import logging

import pymysql

from config import HOST, PORT, USER, PASSWORD, DATABASE


# 起个类名
class DBUtil():

    conn=None

    #创建链接
    @classmethod
    def __create_conn(cls):
        if cls.conn is None:
            cls.conn=pymysql.connect(host=HOST, port=PORT, user=USER, password=PASSWORD,
                           database=DATABASE, charset="utf8")
        return cls.conn

    #关闭链接
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    #查询一个结果
    @classmethod
    def select_one(cls,sql):
        cur=None
        one=None
        try:
            # 创建链接
            cls.conn = cls.__create_conn()
            # 创建游标
            cur = cls.conn.cursor()
            # 执行sql
            cur.execute(sql)
            # 获取结果
            one = cur.fetchone()
        except Exception as err:
            # print("错误信息是：",err)
            logging.info(err)
        finally:
            # 关闭游标
            cur.close()
            # 关闭链接
            cls.__close_conn()
            return one

    #定义增删改
    @classmethod
    def uid_db(cls,sql):
        cur=None
        rows=None
        try:
            # 创建链接
            cls.conn = cls.__create_conn()
            # 创建游标
            cur = cls.conn.cursor()
            # 执行sql
            cur.execute(sql)
            # 成功-提交
            cls.conn.commit()
            #  拿到受影响的行数
            rows=cls.conn.affected_rows()
        except Exception as err:
            # print("错误信息是：",err)
            logging.info(err)
            # 失败-回滚
            cls.conn.rollback()
        finally:
            # 关闭游标
            cur.close()
            # 关闭链接
            cls.__close_conn()
            return f"受影响的行数是：{rows}"


if __name__ == '__main__':

    DBUtil.select_one("select version;")




